'use strict';

const Service = require('egg').Service;

class OrderService extends Service {
  async unpayInfo(tid,status) {
    const rid = this.ctx.request.headers['rid'];
    try{
        const unpaytotal = await this.app.mysql.query('SELECT SUM(orders.total) a FROM orders \
                            INNER JOIN order_restaurant \
                            ON orders.billcode = order_restaurant.oid \
                            WHERE order_restaurant.rid = ? AND orders.paystatus = ?',[rid,0]);
        const unusedtable = await this.app.mysql.query('SELECT COUNT(1) b FROM restaurant_area \
              INNER JOIN area_table ON restaurant_area.aid = area_table.aid \
              INNER JOIN tablez ON tablez.id = area_table.tid \
              WHERE restaurant_area.rid = ? \
              AND tablez.`using` = 0',[rid]);
        if(!tid){
          tid = '*';
        }
        const orderlist = await this.app.mysql.query('SELECT * FROM order_restaurant \
                          INNER JOIN orders ON order_restaurant.oid = orders.billcode \
                          INNER JOIN table_order ON table_order.oid = orders.billcode \
                          WHERE order_restaurant.rid = ? and orders.paystatus = ?',[rid,status])
        for (var i=0;i!=orderlist.length;++i){
          var code = orderlist[i].billcode
          var dids = await this.app.mysql.query('SELECT dids FROM order_dishes WHERE oid = ?',code);
          var dishes = await this.app.mysql.query('select * from dish where id IN (?)',[JSON.parse(dids[0].dids)]);
          orderlist[i].dish = dishes;
        }
        return {
          unused:unusedtable[0].b,
          unpay:unpaytotal[0].a,
          info:orderlist
        };


    }catch(err){
      return 'error';
    }
  }

  async settleOrder(billcode){
    const finishtime = new Date()
    try{
      const result = await this.app.mysql.query('UPDATE orders SET paystatus = 1,finish_time = ? \
                      WHERE billcode = ?',[finishtime,billcode])
      if(result.affectedRows === 1){
        return 'success';
      }else{
        return 'error';
      }
    }catch(err){
      return err.message;
    }
  }
}

module.exports = OrderService;
